<template>
  <div id="addUserFormBox">
    <div class="addHeader">
        <div class="goback" v-if="showTitle">
            <a @click="toUser" class="backUser">返回</a> | 新增用户界面
        </div>
        <div class="goback" v-else>
            <a @click="toUser" class="backUser">返回</a> | 编辑用户界面
        </div>
        <el-form :model="ruleForm" status-icon label-width="100px" class="demo-ruleForm" :rules="rules" ref="ruleForm">
            <el-form-item label="电话号码" class="phoneItem" prop="account">
                <el-input v-model="ruleForm.account" placeholder="请输入电话号码" autocomplete="off" maxlength="11" :disabled="isEdit"></el-input>
            </el-form-item>
            <el-form-item label="员工密码" class="phoneItem" prop="password">
                <el-input v-model="ruleForm.password" placeholder="请输入密码" autocomplete="off" maxlength="20"></el-input>
            </el-form-item>
            <el-form-item label="员工姓名" class="phoneItem" prop="name">
                <el-input v-model="ruleForm.name" placeholder="请输入姓名" autocomplete="off" maxlength="7"></el-input>
            </el-form-item>
            <el-form-item label="员工性别" class="phoneItem">
                <el-select v-model="ruleForm.sex" placeholder="请选择">
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
            </el-form-item>
            <el-form-item label="员工照片" class="phoneItem">
                <el-upload
                    class="avatar-uploader"
                    action="http://localhost:8888/hwy/cater/file/upload"
                    :headers="headers"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="ruleForm.img" :src="ruleForm.img" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-button type="primary" class="subUser" @click="isEdit == false ? addUser('ruleForm'):editUser('ruleForm')">提交用户信息</el-button>
            <!-- <el-button type="primary" class="subUser" @click="editUser('ruleForm')" v-if="isEdit==true">更改用户信息</el-button>
            <el-button type="primary" class="subUser" @click="addUser('ruleForm')" v-if="isEdit==false">提交用户信息</el-button> -->
        </el-form>
    </div>
  </div>
</template>

<script>
import router from '@/router';
import axios from 'axios';
export default {
    data() {
        //校验账号
        var validateAccount = (rule, value, callback) => {
            if (value === '') {
            callback(new Error('账号不能为空'));
            } else {
            //判断输入的是不是正确的手机号格式
            if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
                callback(new Error('请输入正确的手机号'));
            }
            callback();
            }
        };
        //验证姓名字段
        var validateName = (rule, value, callback) =>{
            let reg = /^[\u4e00-\u9fa5]{2,6}$/;
            let name = value;
            if (!reg.test(name) || name=='') {
                callback(new Error('请输入正确的姓名'))
            }else{
                callback();
            }
        }
        //验证密码字段
        var validatePassword = (rule, value, callback) =>{
            if (/[\u4E00-\u9FA5]/g.test(value)) {
                callback(new Error('不能输入汉字'))
            } else if(value == ''){
                callback(new Error('密码不能为空'))
            }else{
                callback();
            }
        }
        return {
            isEdit:false,
            showTitle: true,
            ruleForm:{
                account: '',
                password: '',
                name: '',
                sex: '男',
                img: ''
            },
            options: [
                {
                    value: '男',
                    label: '男'
                }, {
                    value: '女',
                    label: '女'
                }
            ],
            rules: {
                account: [
                    { validator: validateAccount, trigger: 'blur' },
                ],
                password: [
                    // { required: true, message: '密码不能为空', trigger: 'blur' },
                    { validator: validatePassword ,trigger: 'blur'}
                ],
                name: [
                    { validator: validateName, trigger: 'blur'}
                ]
            },
        }
    },

    methods: {
        // headers() {
        //     return {
        //         "Authorization": window.localStorage.getItem("token")
        //     }
        // },

        toUser(){
            router.push("/user")
        },

        handleAvatarSuccess(res, file) {
            // console.log(res)
            // console.log(file)
            this.ruleForm.img = res.data
        },
        //上传照片前对照片格式与大小的判断
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 10;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 10MB!');
            }
            return isJPG && isLt2M;
        },
        //更改用户方法
        editUser(ruleForm){
            console.log("更改用户")
            this.$refs[ruleForm].validate((valid) => {
                if(valid){
                    this.$axios.post("http://localhost:8888/hwy/cater/user/editUser",this.ruleForm)
                        .then((response) =>{
                            console.log(response)
                            if(response.data.code === 1){
                                this.$message({
                                    message: response.data.data,
                                    type: 'success',
                                });
                                router.push("/user")
                            } else {
                                this.$message({
                                    message: response.data.msg,
                                    type: 'error',
                                })
                            }
                        })
                        .catch(function (error) {
                            console.log(error)
                        })
                }else{
                    this.$message({
                        message: '更改失败，请输入正确信息。',
                        type: 'error'
                    });
                }
            })
        },
        //添加用户方法
        addUser(ruleForm) {
            console.log("添加用户")
            this.$refs[ruleForm].validate((valid) => {
                if(valid){
                    this.$axios.post("http://localhost:8888/hwy/cater/user/addUser",this.ruleForm)
                        .then((response) =>{
                            console.log(response)
                            if(response.data.code === 1){
                                this.$message({
                                    message: response.data.data,
                                    type: 'success',
                                });
                                router.push("/user")
                            } else {
                                this.$message({
                                    message: response.data.msg,
                                    type: 'error',
                                })
                            }
                        })
                        .catch(function (error) {
                            console.log(error)
                        })
                }else{
                    this.$message({
                        message: '新增失败，请输入正确信息。',
                        type: 'error'
                    });
                }
            })
        }
    },

    beforeMount() {
        this.$bus.$on("editUserId",(data)=>{
            this.$axios.get("http://localhost:8888/hwy/cater/user/getById/"+ data)
                .then((response) =>{
                    this.showTitle = false;
                    this.ruleForm = response.data.data;
                    this.isEdit = true;
                })
                .catch(function (error) {
                    console.log(error)
                })
        })
    },
    beforeDestroy(){
        this.$bus.$off("editUserId")
    },
    
    computed: {
        headers() {
            return {
                "Authorization": localStorage.getItem("token")
            }
        }
    }
}
</script>

<style scoped>
@import '@/assets/css/user/form.css';
</style>